package net.wantongtech.xa.uploadbasicinfo.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wtkj.exception.BusinessException;
import com.wtkj.vo.dzzf.base.xxjh.MessageSend;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.dao.CommonBaseDao;
import net.wantongtech.xa.uploadbasicinfo.vo.msg.HoldWithTransVo;
import net.wantongtech.xa.uploadbasicinfo.vo.msg.TransactionVo;
import net.wantongtech.xa.uploadbasicinfo.vo.msg.old.TransactionMessage;
import net.wantongtech.xa.uploadbasicinfo.vo.msg.old.WithholdMessage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理中行批量扣款交易服务实现
 *
 * @author MaShibo
 * 日期 :  2020/1/2
 */
@Slf4j
@Service
public class DealWithBOCBatchPayTransService {

    @Resource
    private CommonBaseDao commonBaseDao;

    private ObjectMapper objectMapper = new ObjectMapper();


    public void dealWith() throws IOException {
        List<MessageSend> bocMsgList = commonBaseDao.queryBOCMessageSend();
        log.info("共有{}条中行批量扣款报文数据", bocMsgList.size());
        if (bocMsgList.isEmpty()) {
            return;
        }

        List<String> transactionIdList =
                bocMsgList.stream()
                        .map(v -> {
                            try {
                                return objectMapper.readValue(v.getMsgBody(), WithholdMessage.class);
                            } catch (JsonProcessingException e) {
                                log.error(e.getMessage(), e);
                                throw new BusinessException("JSON格式化失败");
                            }
                        })
                        .flatMap(v -> v.getTransaction().stream())
                        .map(TransactionMessage::getTransactionId)
                        .collect(Collectors.toList());

        log.info("共收集{}个transactionId", transactionIdList.size());

        List<TransactionVo> integratedTransList = commonBaseDao.queryIntegratedTransById(transactionIdList, "BOC");
        HoldWithTransVo transVo = new HoldWithTransVo();
        Long messageId = commonBaseDao.querySeqNetVal("SEQUENCEBOC");
        log.info("获取messageId为：{}", messageId);
        transVo.setMessageId(messageId);
        transVo.setCount(integratedTransList.size());
        long amount = integratedTransList.stream().mapToLong(TransactionVo::getFee).sum();
        transVo.setAmount(amount);
        transVo.setPublishType(0);
        transVo.setTransaction(integratedTransList);
        objectMapper.writeValue(new File("C:\\temp\\boc.json"), transVo);
    }

}
